package com.jetpackframework.rxjetpack.observable;

import com.jetpackframework.rxjetpack.DisposableHelper;
import com.jetpackframework.rxjetpack.Dispose;
import com.jetpackframework.rxjetpack.DisposeImpl;
import com.jetpackframework.rxjetpack.Observer;

public interface ObservableSource<T> {
    void subscribeActual(Observer<? super T> observer);

    public abstract class BaseObserver<T> implements Observer<T>, Dispose,Runnable{

        private T t;
        protected Dispose dispose;
        public BaseObserver(T t){
            this.t = t;
        }

        @Override
        public void dispose() {
            DisposableHelper.dispose(dispose);
        }

        @Override
        public boolean isDispose() {
            return DisposableHelper.isDispose(dispose);
        }

        @Override
        public void onSubscribe(Dispose dispose) {
            this.dispose = dispose;
        }

        public abstract void onNext(T t) throws Exception;

        public abstract void onError(Throwable t);

        public abstract void onComplete();

        @Override
        public final void run() {
            try {
                onSubscribe(new DisposeImpl());
                if (!isDispose()){
                    onNext(t);
                }
            }catch (Exception e){
                onError(e);
            }
            if (isDispose()){
                onComplete();
            }
        }
    }
}
